var shopInfo={
    mapObj: null,
    windowsArr: [],
    marker : [],
    startIcon : null,
    init: function(){
       shopInfo.mapObj = new AMap.Map("mapContainer", {
            resizeEnable: true,
            view: new AMap.View2D({
                resizeEnable: true,
                zoom:13//地图显示的缩放级别
            }),
            keyboardEnable:false
       });

       shopInfo.startIcon = new AMap.Icon({
           // 图标尺寸
           size: new AMap.Size(40, 40),
           // 图标的取图地址
           image: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
           // 图标所用图片大小
           imageSize: new AMap.Size(25, 25),
           // 图标取图偏移量
           //imageOffset: new AMap.Pixel(-9, -3)
       });

        AMap.event.addListener(shopInfo.mapObj,'click',function(e){
            // console.log(e);
            shopInfo.mapObj.clearMap();
            document.getElementById("lngX").value=e.lnglat.getLng();
            document.getElementById("latY").value=e.lnglat.getLat();
            document.getElementById("shop_long").value=e.lnglat.getLng();
            document.getElementById("shop_lat").value=e.lnglat.getLat();
            AMap.service('AMap.Geocoder',function(){//回调函数
                //实例化Geocoder
                geocoder = new AMap.Geocoder({
                    city: ""//城市，默认：“全国”
                });
                var lnglatXY=[e.lnglat.getLng(), e.lnglat.getLat()];//地图上所标点的坐标
                geocoder.getAddress(lnglatXY, function(status, result) {
                    if (status === 'complete' && result.info === 'OK') {
                        //获得了有效的地址信息:
                        //即，result.regeocode.formattedAddress
                        //console.log(result);
                        var city = result.regeocode.formattedAddress;
                    }else{
                        var city = '获取失败';
                        //获取地址失败
                    }
                    document.getElementById("shop_address").value=city;
                    // console.log(city);

                    shopInfo.addMarkerOnMap(lnglatXY)

                });
            })


        });

    },
    addMarkerOnMap:function(lnglatXY) {
        // 将 icon 传入 marker
        var startMarker = new AMap.Marker({
            position: lnglatXY,
            icon: shopInfo.startIcon,
            offset: new AMap.Pixel(-13, -30)
        });
        shopInfo.mapObj.add([startMarker]);
    },
    autoSearch:function() {
        var keywords = document.getElementById("keyword").value;
        var auto;
        //加载输入提示插件
        AMap.service(["AMap.Autocomplete"], function() {
            var autoOptions = {
                city: "" //城市，默认全国
            };
            auto = new AMap.Autocomplete(autoOptions);
            //查询成功时返回查询结果
            if ( keywords.length > 0) {
                auto.search(keywords, function(status, result){
                    shopInfo.autocomplete_CallBack(result);
                });
            }
            else {
                document.getElementById("result1").style.display = "none";
            }
        });
    },
    autocomplete_CallBack:function(data){
        var resultStr = "";
        var tipArr = data.tips;
        if (tipArr&&tipArr.length>0) {
            for (var i = 0; i < tipArr.length; i++) {
                resultStr += "<div id='divid" + (i + 1) + "' onmouseover='shopInfo.openMarkerTipById(" + (i + 1)
                    + ",this)' onclick='shopInfo.selectResult(" + i + ")' onmouseout='shopInfo.onmouseout_MarkerStyle(" + (i + 1)
                    + ",this)' style=\"font-size: 13px;cursor:pointer;padding:5px 5px 5px 5px;\"" + "data=" + tipArr[i].adcode + ">" + tipArr[i].name + "<span style='color:#C1C1C1;'>"+ tipArr[i].district + "</span></div>";
            }
        }
        else  {
            resultStr = " π__π 亲,人家找不到结果!<br />要不试试：<br />1.请确保所有字词拼写正确<br />2.尝试不同的关键字<br />3.尝试更宽泛的关键字";
        }
        document.getElementById("result1").curSelect = -1;
        document.getElementById("result1").tipArr = tipArr;
        document.getElementById("result1").innerHTML = resultStr;
        document.getElementById("result1").style.display = "block";
    },
    openMarkerTipById:function(pointid, thiss){
        thiss.style.background = '#CAE1FF';
    },
    onmouseout_MarkerStyle:function(pointid, thiss){
        thiss.style.background = "";
    },
    selectResult:function(index) {
        if(index<0){
            return;
        }
        if (navigator.userAgent.indexOf("MSIE") > 0) {
            document.getElementById("keyword").onpropertychange = null;
            document.getElementById("keyword").onfocus = focus_callback;
        }
        //截取输入提示的关键字部分
        var text = document.getElementById("divid" + (index + 1)).innerHTML.replace(/<[^>].*?>.*<\/[^>].*?>/g,"");
        var cityCode = document.getElementById("divid" + (index + 1)).getAttribute('data');
        document.getElementById("keyword").value = text;
        document.getElementById("result1").style.display = "none";
        //根据选择的输入提示关键字查询
        shopInfo.mapObj.plugin(["AMap.PlaceSearch"], function() {
            var msearch = new AMap.PlaceSearch();  //构造地点查询类
            AMap.event.addListener(msearch, "complete", shopInfo.placeSearch_CallBack); //查询成功时的回调函数
            msearch.setCity(cityCode);
            //console.log(cityCode);
            msearch.search(text);  //关键字查询查询
        });
    },
    focus_callback:function () {
        if (navigator.userAgent.indexOf("MSIE") > 0) {
            document.getElementById("keyword").onpropertychange = autoSearch;
        }
    },
    placeSearch_CallBack:function (data) {
        //清空地图上的InfoWindow和Marker
        shopInfo.windowsArr = [];
        shopInfo.marker     = [];
        shopInfo.mapObj.clearMap();
        var resultStr1 = "";
        var poiArr = data.poiList.pois;
        var resultCount = poiArr.length;
        for (var i = 0; i < 1; i++) {
            resultStr1 += "<div id='divid" + (i + 1) + "' onmouseover='shopInfo.openMarkerTipById1(" + i + ",this)' onmouseout='shopInfo.onmouseout_MarkerStyle(" + (i + 1) + ",this)' style=\"font-size: 12px;cursor:pointer;padding:0px 0 4px 2px; border-bottom:1px solid #C1FFC1;\"><table><tr><td><img src=\"http://webapi.amap.com/images/" + (i + 1) + ".png\"></td>" + "<td><h3><font color=\"#00a6ac\">名称: " + poiArr[i].name + "</font></h3>";
            resultStr1 += shopInfo.TipContents(poiArr[i].type, poiArr[i].address, poiArr[i].tel) + "</td></tr></table></div>";
            shopInfo.addmarker(i, poiArr[i]);
        }
        shopInfo.mapObj.setFitView();
        shopInfo.mapObj.clearMap()
    },
    openMarkerTipById1:function(pointid, thiss) {
        thiss.style.background = '#CAE1FF';
        windowsArr[pointid].open(shopInfo.mapObj, marker[pointid]);
    },
    addmarker:function (i, d) {
        var lngX = d.location.getLng();
        var latY = d.location.getLat();
        var markerOption = {
            map:shopInfo.mapObj,
            icon:"http://webapi.amap.com/images/" + (i + 1) + ".png",
            position:new AMap.LngLat(lngX, latY)
        };
        var mar = new AMap.Marker(markerOption);
        shopInfo.marker.push(new AMap.LngLat(lngX, latY));

        var infoWindow = new AMap.InfoWindow({
            content:"<div style='padding:0px 0px 0px 4px;font-weight: 200;'><b>" + (i + 1) + ". " + d.name + "</b>" + shopInfo.TipContents(d.type, d.address, d.tel)+'</div>',
            size:new AMap.Size(300, 0),
            autoMove:true,
            offset:new AMap.Pixel(0,-30)
        });
    },
    TipContents:function (type, address, tel) {
        if (type == "" || type == "undefined" || type == null || type == " undefined" || typeof type == "undefined") {
            type = "暂无";
        }
        if (address == "" || address == "undefined" || address == null || address == " undefined" || typeof address == "undefined") {
            address = "暂无";
        }
        if (tel == "" || tel == "undefined" || tel == null || tel == " undefined" || typeof address == "tel") {
            tel = "暂无";
        }
        var str = "  地址：" + address + "<br />  电话：" + tel + " <br />  类型：" + type;
        return str;
    },
    keydown:function (event) {
        var key = (event||window.event).keyCode;
        var result = document.getElementById("result1")
        var cur = result.curSelect;
        if(key===40){//down
            if(cur + 1 < result.childNodes.length){
                if(result.childNodes[cur]){
                    result.childNodes[cur].style.background='';
                }
                result.curSelect=cur+1;
                result.childNodes[cur+1].style.background='#CAE1FF';
                document.getElementById("keyword").value = result.tipArr[cur+1].name;
            }
        }else if(key===38){//up
            if(cur-1>=0){
                if(result.childNodes[cur]){
                    result.childNodes[cur].style.background='';
                }
                result.curSelect=cur-1;
                result.childNodes[cur-1].style.background='#CAE1FF';
                document.getElementById("keyword").value = result.tipArr[cur-1].name;
            }
        }else if(key === 13){
            var res = document.getElementById("result1");
            if(res && res['curSelect'] !== -1){
                shopInfo.selectResult(document.getElementById("result1").curSelect);
            }
        }else{
            shopInfo.autoSearch();
        }
    }
}